package com.wechat.login.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONUtil;
import com.wechat.login.pojo.WeChatUser;
import com.wechat.login.util.WechatUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/wxCheck")
    public String wxSignatureCheck(
           @RequestParam(value = "signature") String signature, 
           @RequestParam(value = "timestamp") String timestamp, 
           @RequestParam(value = "nonce") String nonce, 
           @RequestParam(value = "echostr") String echostr
    ){
        log.info("收到微信校验请求，echostr:{}",echostr);
        return echostr;
    }

    @GetMapping("/wxLogin")
    @ResponseBody
    public void wxLoginPage(HttpServletResponse response) throws Exception{
        String redirectUrl = URLEncoder.encode("https://2a644f9d.r15.cpolar.top/wxCallBack", StandardCharsets.UTF_8);
        String url = " https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx120df5342711e687&redirect_uri="
                +redirectUrl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        response.setContentType("image/png");
        QrCodeUtil.generate(url,300,300,"jpg",response.getOutputStream());
    }
    @RequestMapping("/wxCallBack")
    @ResponseBody
    public String pcCallback(String code, String state, HttpServletRequest request,HttpServletResponse response,
                            HttpSession  session) throws IOException {
        WeChatUser userInfo = WechatUtil.getUserInfo(code);
        return JSONUtil.toJsonStr(userInfo);
    }

}
